#!/bin/bash

# =========================================================
# Agent 自动部署脚本
# 功能：结合环境安装 + 依赖安装 + 服务注册，一键完成部署
# 使用方式：bash deploy_agent.sh
# =========================================================

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 配置
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_PATH="/opt/envs/playenv"
SERVICE_NAME="goofish-agent"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

# ✅ 部署日志配置
DEPLOY_LOG_DIR="${SCRIPT_DIR}/logs"
DEPLOY_LOG_FILE="${DEPLOY_LOG_DIR}/deploy.log"
DEPLOY_REPORT_FILE="${DEPLOY_LOG_DIR}/deploy_report.txt"
DEPLOY_START_TIME=$(date +%s)
DEPLOY_START_TIME_STR=$(date '+%Y-%m-%d %H:%M:%S')

# 确保日志目录存在
mkdir -p "$DEPLOY_LOG_DIR"

# ✅ 强制使用root用户运行服务（不再需要chown操作）
SERVICE_USER="root"

# 初始化部署日志
cat > "$DEPLOY_LOG_FILE" << EOF
========================================================
Agent 部署日志
========================================================
开始时间: $DEPLOY_START_TIME_STR
脚本目录: $SCRIPT_DIR
虚拟环境: $VENV_PATH
服务名称: $SERVICE_NAME
========================================================

EOF

# 日志函数（同时输出到控制台和文件）
log_info() {
    local msg="$1"
    echo -e "${BLUE}[INFO]${NC} $msg"
    echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $msg" >> "$DEPLOY_LOG_FILE"
}

log_success() {
    local msg="$1"
    echo -e "${GREEN}[SUCCESS]${NC} $msg"
    echo "[SUCCESS] $(date '+%Y-%m-%d %H:%M:%S') - $msg" >> "$DEPLOY_LOG_FILE"
}

log_warning() {
    local msg="$1"
    echo -e "${YELLOW}[WARNING]${NC} $msg"
    echo "[WARNING] $(date '+%Y-%m-%d %H:%M:%S') - $msg" >> "$DEPLOY_LOG_FILE"
}

log_error() {
    local msg="$1"
    echo -e "${RED}[ERROR]${NC} $msg"
    echo "[ERROR] $(date '+%Y-%m-%d %H:%M:%S') - $msg" >> "$DEPLOY_LOG_FILE"
}

# ✅ 记录步骤执行结果
declare -A STEP_RESULTS
declare -A STEP_TIMES

log_step_start() {
    local step_name="$1"
    STEP_TIMES["${step_name}_start"]=$(date +%s)
    log_info "开始执行: $step_name"
}

log_step_end() {
    local step_name="$1"
    local status="$2"  # success/failed
    local start_time="${STEP_TIMES[${step_name}_start]}"
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    
    STEP_RESULTS["$step_name"]="$status"
    STEP_TIMES["${step_name}_duration"]=$duration
    
    if [ "$status" == "success" ]; then
        log_success "完成: $step_name (耗时: ${duration}秒)"
    else
        log_error "失败: $step_name (耗时: ${duration}秒)"
    fi
}

# 显示Banner
show_banner() {
    clear
    echo -e "${CYAN}=========================================================${NC}"
    echo -e "${GREEN}   Agent 自动部署脚本${NC}"
    echo -e "${CYAN}=========================================================${NC}"
    echo ""
}

# ✅ 生成部署报告
generate_deploy_report() {
    local deploy_end_time=$(date +%s)
    local total_duration=$((deploy_end_time - DEPLOY_START_TIME))
    local deploy_end_time_str=$(date '+%Y-%m-%d %H:%M:%S')
    
    log_info "正在生成部署报告..."
    
    # 检查服务状态
    local service_status="unknown"
    local service_active="no"
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        service_status="running"
        service_active="yes"
    elif systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
        service_status="installed (not running)"
        service_active="no"
    else
        service_status="not installed"
        service_active="no"
    fi
    
    # 统计成功/失败步骤
    local success_count=0
    local failed_count=0
    for step in "${!STEP_RESULTS[@]}"; do
        if [ "${STEP_RESULTS[$step]}" == "success" ]; then
            ((success_count++))
        else
            ((failed_count++))
        fi
    done
    
    # 生成报告文件
    cat > "$DEPLOY_REPORT_FILE" << EOF
========================================================
Agent 部署报告
========================================================
生成时间: $deploy_end_time_str
主机名称: $(hostname)
主机IP: $(hostname -I | awk '{print $1}')
操作系统: $(cat /etc/os-release | grep PRETTY_NAME | cut -d'"' -f2)
========================================================

📋 部署信息
----------------------------------------
开始时间: $DEPLOY_START_TIME_STR
结束时间: $deploy_end_time_str
总耗时: ${total_duration}秒 (约 $((total_duration / 60))分钟)
脚本目录: $SCRIPT_DIR
虚拟环境: $VENV_PATH
服务名称: $SERVICE_NAME

📊 执行摘要
----------------------------------------
总步骤数: $((success_count + failed_count))
成功步骤: $success_count
失败步骤: $failed_count
成功率: $(( success_count * 100 / (success_count + failed_count) ))%

📝 步骤详情
----------------------------------------
EOF

    # 添加每个步骤的详细信息
    for step in "步骤0-清理旧部署" "步骤1-更新系统" "步骤2-安装Python" "步骤3-安装字体" \
                "步骤4-安装Playwright依赖" "步骤5-安装Xvfb" "步骤6-创建浏览器目录" \
                "步骤7-创建虚拟环境" "步骤8-安装Python依赖" "步骤9-安装Chromium" \
                "步骤10-注册系统服务"; do
        local status="${STEP_RESULTS[$step]:-未执行}"
        local duration="${STEP_TIMES[${step}_duration]:-0}"
        local status_icon
        
        if [ "$status" == "success" ]; then
            status_icon="✅"
        elif [ "$status" == "failed" ]; then
            status_icon="❌"
        else
            status_icon="⏸️"
        fi
        
        printf "%-30s %s %-10s (耗时: %3ds)\n" "$step" "$status_icon" "$status" "$duration" >> "$DEPLOY_REPORT_FILE"
    done
    
    # 添加服务状态信息
    cat >> "$DEPLOY_REPORT_FILE" << EOF

🔧 服务状态
----------------------------------------
服务名称: $SERVICE_NAME
服务状态: $service_status
是否运行: $service_active
服务文件: $SERVICE_FILE

🌐 环境信息
----------------------------------------
Python版本: $(python3 --version 2>/dev/null || echo "未安装")
虚拟环境: $([ -d "$VENV_PATH" ] && echo "已创建" || echo "未创建")
Playwright: $([ -d "/opt/playwright-browsers" ] && echo "已安装" || echo "未安装")
Xvfb: $(command -v xvfb-run &>/dev/null && echo "已安装" || echo "未安装")

📁 目录结构
----------------------------------------
项目目录: $SCRIPT_DIR
日志目录: $DEPLOY_LOG_DIR
浏览器目录: /opt/playwright-browsers
用户数据: /opt/user_data/default

EOF

    # 如果有失败步骤，添加错误摘要
    if [ $failed_count -gt 0 ]; then
        cat >> "$DEPLOY_REPORT_FILE" << EOF
⚠️  失败步骤
----------------------------------------
EOF
        for step in "${!STEP_RESULTS[@]}"; do
            if [ "${STEP_RESULTS[$step]}" == "failed" ]; then
                echo "❌ $step" >> "$DEPLOY_REPORT_FILE"
            fi
        done
        echo "" >> "$DEPLOY_REPORT_FILE"
        cat >> "$DEPLOY_REPORT_FILE" << EOF
建议操作:
1. 查看详细日志: cat $DEPLOY_LOG_FILE
2. 检查网络连接是否正常
3. 确认服务器有足够的磁盘空间
4. 重新运行部署脚本

EOF
    fi
    
    # 添加常用命令
    cat >> "$DEPLOY_REPORT_FILE" << EOF
📌 常用命令
----------------------------------------
启动服务: sudo systemctl start $SERVICE_NAME
停止服务: sudo systemctl stop $SERVICE_NAME
重启服务: sudo systemctl restart $SERVICE_NAME
查看状态: sudo systemctl status $SERVICE_NAME
查看日志: sudo journalctl -u $SERVICE_NAME -f
Agent日志: tail -f $SCRIPT_DIR/logs/agent.log
部署日志: cat $DEPLOY_LOG_FILE

========================================================
报告结束
========================================================
EOF

    log_success "部署报告已生成: $DEPLOY_REPORT_FILE"
    
    # 如果有失败步骤，显示警告
    if [ $failed_count -gt 0 ]; then
        echo ""
        log_warning "检测到 $failed_count 个步骤失败，请查看报告了解详情"
        log_warning "报告路径: $DEPLOY_REPORT_FILE"
    fi
}

# 步骤1: 更新系统
step1_update_system() {
    log_info "🚀 [1/10] 更新系统..."
    sudo DEBIAN_FRONTEND=noninteractive apt update -y > /dev/null 2>&1
    sudo DEBIAN_FRONTEND=noninteractive apt upgrade -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" > /dev/null 2>&1
    log_success "系统更新完成"
}

# 步骤2: 安装Python
step2_install_python() {
    log_info "📦 [2/10] 安装 Python 与基础依赖..."
    sudo DEBIAN_FRONTEND=noninteractive apt install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
        python3 python3-pip python3-venv python-is-python3 > /dev/null 2>&1
    
    # 验证 pip 是否安装成功
    if ! command -v pip3 &> /dev/null && ! command -v pip &> /dev/null; then
        log_warning "pip 安装失败，尝试手动修复..."
        sudo apt install --reinstall -y python3-pip > /dev/null 2>&1 || true
    fi
    
    if command -v python &> /dev/null; then
        PYTHON_VERSION=$(python --version 2>&1)
        log_success "Python 安装完成: $PYTHON_VERSION"
    else
        log_error "Python 安装失败"
        exit 1
    fi
}

# 步骤3: 安装中文字体
step3_install_fonts() {
    log_info "📦 [3/10] 安装中文字体..."
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
        fonts-wqy-zenhei fonts-wqy-microhei fonts-noto-cjk fonts-liberation > /dev/null 2>&1
    fc-cache -fv > /dev/null 2>&1
    log_success "中文字体安装完成"
}

# 步骤4: 安装Playwright系统依赖
step4_install_playwright_deps() {
    log_info "🧩 [4/10] 安装 Playwright 所需系统依赖..."
    sudo DEBIAN_FRONTEND=noninteractive apt install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
        wget git curl libnss3 libx11-xcb1 libxcomposite1 libxdamage1 libxrandr2 \
        libxkbcommon0 libpango-1.0-0 libatk1.0-0t64 libcups2t64 libgbm1 libasound2t64 fonts-liberation \
        libgtk-3-0 libdrm2 libxshmfence1 libxfixes3 libxext6 > /dev/null 2>&1
    log_success "Playwright 系统依赖安装完成"
}

# 步骤5: 安装Xvfb
step5_install_xvfb() {
    log_info "🖥️ [5/10] 安装虚拟屏幕 Xvfb..."
    sudo DEBIAN_FRONTEND=noninteractive apt install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
        xvfb > /dev/null 2>&1
    log_success "Xvfb 安装完成"
}

# 步骤6: 创建浏览器缓存目录
step6_create_browser_dir() {
    log_info "📂 [6/10] 创建浏览器缓存目录..."
    sudo mkdir -p /opt/playwright-browsers
    sudo chmod -R 777 /opt/playwright-browsers
    
    # ✅ 创建 Chrome 用户数据目录（root用户，无需chown）
    log_info "创建Chrome用户数据目录..."
    sudo mkdir -p /opt/user_data/default
    sudo chmod -R 755 /opt/user_data
    log_success "Chrome用户数据目录创建完成"
    
    # 永久写入环境变量
    if ! grep -q "PLAYWRIGHT_BROWSERS_PATH" ~/.bashrc; then
        echo 'export PLAYWRIGHT_BROWSERS_PATH=/opt/playwright-browsers' >> ~/.bashrc
    fi
    export PLAYWRIGHT_BROWSERS_PATH=/opt/playwright-browsers
    log_success "浏览器缓存目录创建完成"
}

# 步骤7: 创建Python虚拟环境
step7_create_venv() {
    log_info "🌱 [7/10] 创建虚拟环境..."
    sudo mkdir -p /opt/envs && sudo chmod -R 777 /opt/envs
    if [ ! -d "$VENV_PATH" ]; then
        python -m venv "$VENV_PATH"
        log_success "虚拟环境创建成功"
    else
        log_success "虚拟环境已存在"
    fi
}

# 步骤8: 安装Playwright和项目依赖
step8_install_dependencies() {
    log_info "📦 [8/10] 安装 Playwright 和项目依赖..."
    
    # 激活虚拟环境
    if [ ! -f "$VENV_PATH/bin/activate" ]; then
        log_error "虚拟环境不存在"
        exit 1
    fi
    
    source "$VENV_PATH/bin/activate"
    
    # 安装基础包
    pip install -U pip setuptools > /dev/null 2>&1
    pip install playwright loguru > /dev/null 2>&1
    
    # 安装项目依赖
    if [ -f "$SCRIPT_DIR/requirements.txt" ]; then
        pip install -r "$SCRIPT_DIR/requirements.txt" > /dev/null 2>&1
        log_success "项目依赖安装完成"
    else
        log_warning "未找到 requirements.txt"
    fi
    
    log_success "Playwright 和依赖安装完成"
}

# 步骤9: 安装Chromium浏览器
step9_install_chromium() {
    log_info "🌐 [9/10] 安装 Chromium 浏览器..."
    
    source "$VENV_PATH/bin/activate"
    export PLAYWRIGHT_BROWSERS_PATH=/opt/playwright-browsers
    
    PLAYWRIGHT_BROWSERS_PATH=/opt/playwright-browsers playwright install chromium > /dev/null 2>&1
    
    # 检测 Chromium 版本
    CHROMIUM_DIR=$(find /opt/playwright-browsers -maxdepth 1 -type d -name "chromium-*" | head -n 1)
    
    if [ -z "$CHROMIUM_DIR" ]; then
        log_error "Chromium 安装失败"
        exit 1
    fi
    
    sudo chmod -R 777 /opt/playwright-browsers
    log_success "Chromium 浏览器安装完成"
}

# 步骤10: 注册为系统服务
step10_install_service() {
    log_info "⚙️ [10/10] 注册为系统服务..."
    
    # ✅ 强制使用root用户运行服务
    SERVICE_USER="root"
    
    # 停止旧服务
    if systemctl list-unit-files | grep -q "^${SERVICE_NAME}.service"; then
        sudo systemctl stop "$SERVICE_NAME" 2>/dev/null || true
        sudo systemctl disable "$SERVICE_NAME" 2>/dev/null || true
        sudo rm -f "$SERVICE_FILE"
        sudo systemctl daemon-reload
    fi
    
    # 创建启动脚本
    SERVICE_START_SCRIPT="/opt/${SERVICE_NAME}_start.sh"
    
    sudo bash -c "cat > $SERVICE_START_SCRIPT" <<EOF
#!/bin/bash
# Agent服务启动脚本

# 设置环境变量
export PLAYWRIGHT_BROWSERS_PATH=/opt/playwright-browsers

# 激活虚拟环境并运行Agent
source $VENV_PATH/bin/activate
cd $SCRIPT_DIR

# 使用xvfb-run启动
exec xvfb-run -a -s "-screen 0 1920x1080x24 -ac +extension GLX +render -noreset" python main.py
EOF
    
    sudo chmod +x "$SERVICE_START_SCRIPT"
    
    # 创建服务文件
    sudo bash -c "cat > $SERVICE_FILE" <<EOF
[Unit]
Description=Goofish Agent Service
After=network.target

[Service]
Type=simple
User=$SERVICE_USER
WorkingDirectory=$SCRIPT_DIR
ExecStart=$SERVICE_START_SCRIPT
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
    
    # 重新加载并启用服务
    sudo systemctl daemon-reload
    sudo systemctl enable "$SERVICE_NAME" > /dev/null 2>&1
    
    # ✅ 确保 logs 目录存在（root用户，无需chown）
    log_info "创建日志目录..."
    sudo mkdir -p "$SCRIPT_DIR/logs"
    sudo chmod -R 755 "$SCRIPT_DIR/logs"
    log_success "日志目录已创建"
    
    # ✅ 确保 Chrome 用户数据目录存在（root用户，无需chown）
    log_info "创建Chrome用户数据目录..."
    sudo mkdir -p /opt/user_data/default
    sudo chmod -R 755 /opt/user_data
    log_success "Chrome用户数据目录已创建"
    
    log_success "系统服务注册完成"
}

# 步骤0: 清理旧部署（如果存在）
step0_cleanup_old_deployment() {
    log_info "📋 [0/10] 检查并清理旧部署..."
    
    local needs_cleanup=false
    
    # 1. 检查是否存在旧服务
    if systemctl list-unit-files | grep -q "^${SERVICE_NAME}.service"; then
        log_warning "检测到已存在的服务: ${SERVICE_NAME}"
        needs_cleanup=true
        
        # 停止服务
        if systemctl is-active --quiet "$SERVICE_NAME"; then
            log_info "正在停止旧服务..."
            sudo systemctl stop "$SERVICE_NAME" 2>/dev/null || true
            sleep 2
        fi
        
        # 禁用服务
        if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
            log_info "正在禁用旧服务..."
            sudo systemctl disable "$SERVICE_NAME" 2>/dev/null || true
        fi
        
        # 删除服务文件
        if [ -f "$SERVICE_FILE" ]; then
            log_info "正在删除旧服务文件..."
            sudo rm -f "$SERVICE_FILE"
        fi
        
        # 删除启动脚本
        local old_start_script="/opt/${SERVICE_NAME}_start.sh"
        if [ -f "$old_start_script" ]; then
            sudo rm -f "$old_start_script"
        fi
        
        sudo systemctl daemon-reload
        log_success "旧服务已清理"
    fi
    
    # ✅ 1.5. 强制清理所有相关进程（确保没有残留）
    log_info "检查并清理残留进程..."
    
    # 查找并终止Agent进程
    local agent_pids=$(pgrep -f "python.*main.py" 2>/dev/null || true)
    if [ -n "$agent_pids" ]; then
        log_warning "发现残留的Agent进程: $agent_pids"
        sudo pkill -9 -f "python.*main.py" 2>/dev/null || true
        sleep 1
        log_success "Agent进程已清理"
    fi
    
    # 清理Chrome/Chromium进程（避免profile锁定）
    local chrome_pids=$(pgrep -f "chrome|chromium" 2>/dev/null || true)
    if [ -n "$chrome_pids" ]; then
        log_warning "发现残留的Chrome进程: $chrome_pids"
        sudo pkill -9 -f "chrome" 2>/dev/null || true
        sudo pkill -9 -f "chromium" 2>/dev/null || true
        sleep 1
        log_success "Chrome进程已清理"
    fi
    
    # ✅ 1.6. 备份并清理Chrome profile
    local user_data_dir="/opt/user_data/default"
    if [ -d "$user_data_dir" ]; then
        # 备份浏览器配置文件夹
        local backup_timestamp=$(date +%Y%m%d_%H%M%S)
        local backup_dir="/opt/user_data/default_backup_${backup_timestamp}"
        log_info "备份浏览器配置文件夹..."
        if sudo mv "$user_data_dir" "$backup_dir" 2>/dev/null; then
            log_success "已备份浏览器配置文件夹到: $backup_dir"
        else
            log_warning "备份浏览器配置文件夹失败，继续清理锁定文件..."
        fi
    fi
    
    # 2. 清理旧代码（仅当不是新解压的代码时）
    # ✅ 检查代码是否是刚解压的（检查目录的创建时间，而不是文件的修改时间）
    # ⚠️ 注意：mv 不会改变文件的 mtime，但会改变目录的 ctime
    local skip_code_cleanup=false
    if [ -d "$SCRIPT_DIR" ]; then
        # 检查目录的状态改变时间（ctime），mv 会更新这个时间
        local dir_age=$(($(date +%s) - $(stat -c %Z "$SCRIPT_DIR" 2>/dev/null || echo 0)))
        if [ $dir_age -lt 60 ]; then  # 如果目录在最近1分钟内有状态变化
            log_info "检测到新部署的代码（目录年龄: ${dir_age}秒），跳过代码清理"
            skip_code_cleanup=true
        fi
    fi
    
    if [ "$skip_code_cleanup" = false ] && [ -d "$SCRIPT_DIR" ] && [ -f "$SCRIPT_DIR/main.py" ]; then
        log_warning "检测到旧的项目文件: $SCRIPT_DIR"
        needs_cleanup=true
        
        # 创建备份
        local backup_dir="/tmp/agent_backup_$(date +%Y%m%d_%H%M%S)"
        log_info "正在备份旧代码到: $backup_dir"
        sudo mkdir -p "$backup_dir"
        
        # 只备份重要文件（不包括日志、截图等）
        if [ -f "$SCRIPT_DIR/config.json" ]; then
            sudo cp "$SCRIPT_DIR/config.json" "$backup_dir/" 2>/dev/null || true
        fi
        if [ -f "$SCRIPT_DIR/state.json" ]; then
            sudo cp "$SCRIPT_DIR/state.json" "$backup_dir/" 2>/dev/null || true
        fi
        if [ -d "$SCRIPT_DIR/logs" ]; then
            sudo mkdir -p "$backup_dir/logs"
            sudo cp "$SCRIPT_DIR/logs/"*.log "$backup_dir/logs/" 2>/dev/null || true
        fi
        
        log_success "重要文件已备份"
        
        # 清理旧代码（保留备份的配置文件）
        log_info "正在清理旧代码..."
        
        # 删除Python缓存
        find "$SCRIPT_DIR" -type d -name "__pycache__" -exec sudo rm -rf {} + 2>/dev/null || true
        find "$SCRIPT_DIR" -type f -name "*.pyc" -exec sudo rm -f {} + 2>/dev/null || true
        
        # 删除旧的Python文件（但保留目录结构）
        sudo find "$SCRIPT_DIR" -maxdepth 1 -type f -name "*.py" -delete 2>/dev/null || true
        sudo find "$SCRIPT_DIR" -maxdepth 1 -type f -name "*.sh" -delete 2>/dev/null || true
        sudo find "$SCRIPT_DIR" -maxdepth 1 -type f -name "*.js" -delete 2>/dev/null || true
        
        # 删除旧的模块目录
        if [ -d "$SCRIPT_DIR/core" ]; then
            sudo rm -rf "$SCRIPT_DIR/core"
        fi
        if [ -d "$SCRIPT_DIR/modules" ]; then
            sudo rm -rf "$SCRIPT_DIR/modules"
        fi
        if [ -d "$SCRIPT_DIR/utils" ]; then
            sudo rm -rf "$SCRIPT_DIR/utils"
        fi
        
        log_success "旧代码已清理（配置文件已备份）"
        log_warning "备份位置: $backup_dir"
    elif [ "$skip_code_cleanup" = true ]; then
        log_success "代码是新解压的，跳过清理步骤"
    fi
    
    # 3. 检查虚拟环境是否存在
    if [ -d "$VENV_PATH" ]; then
        log_info "检测到已存在的虚拟环境: $VENV_PATH"
        # 不删除虚拟环境，可以复用，节省时间
        log_success "将复用现有虚拟环境"
    fi
    
    if [ "$needs_cleanup" = true ]; then
        log_success "旧部署清理完成"
    else
        log_success "未检测到旧部署，继续全新安装"
    fi
    
    echo ""
}

# 主部署流程
main() {
    show_banner
    
    # 检查是否在项目目录
    if [ ! -f "$SCRIPT_DIR/main.py" ]; then
        log_error "未找到 main.py 文件"
        log_error "当前目录: $SCRIPT_DIR"
        log_error "请确保在项目根目录执行此脚本"
        exit 1
    fi
    
    log_info "开始部署 Agent..."
    echo ""
    
    # 执行所有步骤（带执行结果跟踪）
    log_step_start "步骤0-清理旧部署"
    if step0_cleanup_old_deployment; then
        log_step_end "步骤0-清理旧部署" "success"
    else
        log_step_end "步骤0-清理旧部署" "failed"
    fi
    
    log_step_start "步骤1-更新系统"
    if step1_update_system; then
        log_step_end "步骤1-更新系统" "success"
    else
        log_step_end "步骤1-更新系统" "failed"
    fi
    
    log_step_start "步骤2-安装Python"
    if step2_install_python; then
        log_step_end "步骤2-安装Python" "success"
    else
        log_step_end "步骤2-安装Python" "failed"
    fi
    
    log_step_start "步骤3-安装字体"
    if step3_install_fonts; then
        log_step_end "步骤3-安装字体" "success"
    else
        log_step_end "步骤3-安装字体" "failed"
    fi
    
    log_step_start "步骤4-安装Playwright依赖"
    if step4_install_playwright_deps; then
        log_step_end "步骤4-安装Playwright依赖" "success"
    else
        log_step_end "步骤4-安装Playwright依赖" "failed"
    fi
    
    log_step_start "步骤5-安装Xvfb"
    if step5_install_xvfb; then
        log_step_end "步骤5-安装Xvfb" "success"
    else
        log_step_end "步骤5-安装Xvfb" "failed"
    fi
    
    log_step_start "步骤6-创建浏览器目录"
    if step6_create_browser_dir; then
        log_step_end "步骤6-创建浏览器目录" "success"
    else
        log_step_end "步骤6-创建浏览器目录" "failed"
    fi
    
    log_step_start "步骤7-创建虚拟环境"
    if step7_create_venv; then
        log_step_end "步骤7-创建虚拟环境" "success"
    else
        log_step_end "步骤7-创建虚拟环境" "failed"
    fi
    
    log_step_start "步骤8-安装Python依赖"
    if step8_install_dependencies; then
        log_step_end "步骤8-安装Python依赖" "success"
    else
        log_step_end "步骤8-安装Python依赖" "failed"
    fi
    
    log_step_start "步骤9-安装Chromium"
    if step9_install_chromium; then
        log_step_end "步骤9-安装Chromium" "success"
    else
        log_step_end "步骤9-安装Chromium" "failed"
    fi
    
    log_step_start "步骤10-注册系统服务"
    if step10_install_service; then
        log_step_end "步骤10-注册系统服务" "success"
    else
        log_step_end "步骤10-注册系统服务" "failed"
    fi
    
    # ✅ 生成部署报告
    generate_deploy_report
    
    echo ""
    echo -e "${CYAN}=========================================================${NC}"
    echo -e "${GREEN}🎉 部署完成！${NC}"
    echo -e "${CYAN}=========================================================${NC}"
    echo ""
    log_info "服务名称: ${SERVICE_NAME}"
    log_info "服务状态: 已安装并启用开机自启"
    echo ""
    log_info "部署日志: ${DEPLOY_LOG_FILE}"
    log_info "部署报告: ${DEPLOY_REPORT_FILE}"
    echo ""
    log_info "常用命令："
    echo -e "  ${CYAN}启动服务:${NC} sudo systemctl start ${SERVICE_NAME}"
    echo -e "  ${CYAN}停止服务:${NC} sudo systemctl stop ${SERVICE_NAME}"
    echo -e "  ${CYAN}查看状态:${NC} sudo systemctl status ${SERVICE_NAME}"
    echo -e "  ${CYAN}查看日志:${NC} sudo journalctl -u ${SERVICE_NAME} -f"
    echo -e "  ${CYAN}Agent日志:${NC} tail -f ${SCRIPT_DIR}/logs/agent.log"
    echo ""
}

# 执行主函数
main "$@"

